from targetmonitoring.abstracts.abstract_target_monitor_client import AbstractTargetMonitorClient
from console_target_management_client import ConsoleTargetManagementClient
from console_submit_to_target_client import ConsoleSubmitToTargetClient
from bsccommonlib.csv_persister import CsvPersister
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib.cbook as cbook
from threading import Thread
import targetmonitoring.utils as utils
import texttable as tt
from bsccommonlib.generate_id import generate_tmp_id

class ConsoleTargetMonitorClient(AbstractTargetMonitorClient):
    def __init__(self, target_csv_file):
        super(ConsoleTargetMonitorClient, self).__init__(target_csv_file)

    def _on_display_requested(self, selection_list):
        print "<---------Target Monitor----------->"
        for menu_item in selection_list:
            print "%s" % (menu_item)

        self._fire_item_selected(self._get_selection(len(selection_list)))

    @utils.clear_console
    def _on_target_list_display_request(self, target_list):
        entry_owner = raw_input("Owner: ").strip()
        table = tt.Texttable()
        data = [[]]

        for target_item in target_list:
            if entry_owner == '' or target_item.owner.lower() == entry_owner.lower():
                data.append([  target_item.id
                             , target_item.name
                             , target_item.status
                             , target_item.need_work
                             , target_item.initial_status
                             , target_item.actual_target
                             , target_item.days_left])

        table.add_rows(data)
        table.set_cols_align(['r', 'r', 'r', 'r', 'r', 'r', 'r'])
        table.set_cols_width([5, 25, 10, 10, 10, 10, 10])
        table.header(['ID', 'Name', 'Status', 'Need Work', 'Initial Value', 'Actual Target', 'Days Left'])
        print table.draw()

    @utils.clear_console
    def _on_manage_target_client_request(self):
        return ConsoleTargetManagementClient(self.csv_file)

    @utils.clear_console
    def _on_submit_to_target_client_request(self, csv_file, target_object):
        return ConsoleSubmitToTargetClient(csv_file, target_object)

    def _on_submit_entry_request(self):
        target_id = raw_input('Enter target id to submit:')
        try:
            target_id = int(target_id)
            self._fire_submit_entry_completed(target_id)
        except ValueError:
            pass

    def _on_display_chart_entry_request(self):
        target_id = raw_input('Enter target id to chart:')
        try:
            target_id = int(target_id)
            self._fire_display_chart_entry_completed(target_id)
        except ValueError:
            pass

    @utils.clear_console
    def _on_chart_display_request(self, data_list):
        try:
            Thread(target=display_chart, args=(data_list,)).start()
        except Exception, errtxt:
            print errtxt

    @utils.clear_console
    def _on_exit(self):
        pass

    def _get_selection(self, ra):
        chosen = raw_input("Select " + str(range(ra)) + ":")
        try:
            chosen = int(chosen)
            if 0 <= chosen < ra :
                return chosen
        except ValueError:
            pass

        return None

def display_chart(data_list, *args):
    tmp_file_name = '/tmp/_' + generate_tmp_id() + '.csv'
    import os
    persister = CsvPersister(tmp_file_name)
    last_submit_index = None
    for i, data in enumerate(data_list):
        persister.add(data)
        if last_submit_index is None and data.submit_value is None:
            last_submit_index = i

    if last_submit_index is None:
        last_submit_index = len(data_list) - 1

    datafile = cbook.get_sample_data(tmp_file_name, asfileobj=False)
    r = mlab.csv2rec(datafile)
    r.sort()
    r2 = r[:last_submit_index]

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(r.date, r.target_value, 'o-')
    ax.plot(r2.date, r2.submit_value, 'o-')
    fig.autofmt_xdate()
    plt.show()
    os.remove(tmp_file_name)



if __name__ == '__main__':
    client = ConsoleTargetMonitorClient('/home/bsceran/Dropbox/Data/target01.csv')
    client.start()
